/**
* <p>Title: AvoidDuplicateSubmissionInterceptor.java</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2015</p>
* <p>Company: SiySoft</p>
* @author liguanghui
* @date 2015年5月25日
* @version 1.0
*/
package com.siysoft.util;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class AvoidDuplicateSubmissionInterceptor
  extends HandlerInterceptorAdapter
{
  private static final Logger logger = Logger.getLogger(AvoidDuplicateSubmissionInterceptor.class);
  
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
    throws Exception
  {
    HandlerMethod handlerMethod = (HandlerMethod)handler;
    Method method = handlerMethod.getMethod();
    
    AvoidDuplicateSubmission annotation = (AvoidDuplicateSubmission)method.getAnnotation(AvoidDuplicateSubmission.class);
    if (annotation != null)
    {
      boolean needSaveSession = annotation.needSaveToken();
      if (needSaveSession) {
        request.getSession(false).setAttribute("token", TokenProcessor.getInstance().generateToken(request));
      }
      boolean needRemoveSession = annotation.needRemoveToken();
      if (needRemoveSession)
      {
        if (isRepeatSubmit(request))
        {
          logger.debug("表单重复提交拦截器" + request.getServletPath() + "]");
          response.sendRedirect(request.getContextPath() + "/success.htm");
          return false;
        }
        request.getSession(false).removeAttribute("token");
      }
    }
    return true;
  }
  
  private boolean isRepeatSubmit(HttpServletRequest request)
  {
    String serverToken = (String)request.getSession(false).getAttribute("token");
    if (serverToken == null) {
      return true;
    }
    String clinetToken = request.getParameter("token");
    if (clinetToken == null) {
      return true;
    }
    if (!serverToken.equals(clinetToken)) {
      return true;
    }
    return false;
  }
}
